from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from django.utils import timezone
from django.db import transaction
from .models import Resume, ResumeTemplate, ResumeAnalysis, JobRecommendation, CompanyRecommendation
from .serializers import (
    ResumeSerializer, ResumeTemplateSerializer, ResumeAnalysisSerializer,
    ResumeAnalysisCreateSerializer, ResumeAnalysisResultSerializer
)
from .services.rag import search_templates_by_keyword
from .services.resume_analyzer import resume_analyzer
from rest_framework.permissions import AllowAny, IsAuthenticated

class ResumeViewSet(viewsets.ModelViewSet):
    permission_classes = [IsAuthenticated]
    queryset = Resume.objects.all().order_by('-created_at')
    serializer_class = ResumeSerializer

    def perform_create(self, serializer):
        serializer.save()

    def get_queryset(self):
        queryset = super().get_queryset()
        # ... 你的其他筛选逻辑 ...
        return queryset

class ResumeTemplateViewSet(viewsets.ModelViewSet):
    """
    简历模板的增删改查接口
    """
    permission_classes = [AllowAny]
    queryset = ResumeTemplate.objects.all().order_by('-created_at')
    serializer_class = ResumeTemplateSerializer

    # 可选：支持按类型、标签等筛选
    def get_queryset(self):
        queryset = super().get_queryset()
        template_type = self.request.query_params.get('template_type')
        tags = self.request.query_params.get('tags')
        if template_type:
            queryset = queryset.filter(template_type=template_type)
        if tags:
            for tag in tags.split(','):
                queryset = queryset.filter(tags__icontains=tag)
        return queryset

    @action(detail=False, methods=['get'])
    def rag_search(self, request):
        """
        临时关键词检索接口：用关键词包含方式检索简历模板
        GET参数：q=检索文本
        """
        query = request.query_params.get('q', '')
        if not query:
            return Response({'detail': '缺少查询参数q'}, status=400)
        # 调用关键词检索函数，获取最相关的模板
        results = search_templates_by_keyword(query)
        # 序列化结果并返回
        serializer = self.get_serializer(results, many=True)
        return Response(serializer.data)


class ResumeAnalysisViewSet(viewsets.ModelViewSet):
    """
    简历分析视图集
    """
    permission_classes = [IsAuthenticated]
    queryset = ResumeAnalysis.objects.all().order_by('-created_at')
    serializer_class = ResumeAnalysisSerializer

    def get_queryset(self):
        # 只在读取（list/retrieve）时过滤
        if self.action in ['list', 'retrieve']:
            return super().get_queryset().filter(user=self.request.user)
        return super().get_queryset()
    
    def get_serializer_class(self):
        """根据不同的操作使用不同的序列化器"""
        if self.action == 'create':
            return ResumeAnalysisCreateSerializer
        elif self.action in ['retrieve', 'list']:
            return ResumeAnalysisResultSerializer
        return ResumeAnalysisSerializer

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)  # self.request.user 必须是 auth_user 的实例
    
    def create(self, request, *args, **kwargs):
        """创建简历分析任务"""
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        
        # 创建分析记录
        analysis = serializer.save()
        
        # 异步执行分析任务
        self._analyze_resume_async(analysis)
        
        return Response({
            'id': analysis.id,
            'status': analysis.status,
            'message': '简历分析任务已创建，请稍后查看结果'
        }, status=status.HTTP_201_CREATED)
    
    def _analyze_resume_async(self, analysis):
        """异步分析简历"""
        try:
            # 获取文件路径
            file_path = analysis.resume_file.path
            
            # 执行分析
            result = resume_analyzer.analyze_resume(file_path, analysis.original_filename)
            
            if result['success']:
                # 更新分析结果
                analysis.extracted_text = result['extracted_text']
                analysis.analysis_result = result['analysis_result']
                analysis.improvement_suggestions = result['improvement_suggestions']
                analysis.recommended_positions = result['recommended_positions']
                analysis.recommended_companies = result['recommended_companies']
                analysis.status = 'completed'
                analysis.completed_at = timezone.now()
                
                # 创建职位推荐记录
                self._create_job_recommendations(analysis, result['recommended_positions'])
                
                # 创建公司推荐记录
                self._create_company_recommendations(analysis, result['recommended_companies'])
                
            else:
                analysis.status = 'failed'
                analysis.error_message = result.get('error', '分析失败')
            
            analysis.save()
            
        except Exception as e:
            analysis.status = 'failed'
            analysis.error_message = str(e)
            analysis.save()
    
    def _create_job_recommendations(self, analysis, positions):
        """创建职位推荐记录"""
        for pos in positions:
            JobRecommendation.objects.create(
                analysis=analysis,
                position_title=pos['title'],
                company_name='',  # 可以从职位信息中提取
                salary_range='',
                location='',
                requirements='',
                match_score=pos.get('match_score', 0.0),
                reason=pos.get('match_reason', '')
            )
    
    def _create_company_recommendations(self, analysis, companies):
        """创建公司推荐记录"""
        for company in companies:
            CompanyRecommendation.objects.create(
                analysis=analysis,
                company_name=company['name'],
                industry=company.get('industry', ''),
                company_size='',
                location='',
                description='',
                match_score=company.get('match_score', 0.0),
                reason=company.get('match_reason', '')
            )
    
    @action(detail=True, methods=['get'])
    def status(self, request, pk=None):
        """查询分析状态"""
        try:
            analysis = self.get_object()
            return Response({
                'id': analysis.id,
                'status': analysis.status,
                'error_message': analysis.error_message,
                'created_at': analysis.created_at,
                'completed_at': analysis.completed_at
            })
        except ResumeAnalysis.DoesNotExist:
            return Response({'error': '分析记录不存在'}, status=status.HTTP_404_NOT_FOUND)
    
    @action(detail=True, methods=['post'])
    def retry(self, request, pk=None):
        """重试分析"""
        try:
            analysis = self.get_object()
            
            # 重置状态
            analysis.status = 'pending'
            analysis.error_message = ''
            analysis.save()
            
            # 重新执行分析
            self._analyze_resume_async(analysis)
            
            return Response({
                'message': '分析任务已重新启动'
            })
            
        except ResumeAnalysis.DoesNotExist:
            return Response({'error': '分析记录不存在'}, status=status.HTTP_404_NOT_FOUND)
    
    @action(detail=False, methods=['get'])
    def statistics(self, request):
        """获取分析统计信息"""
        user_analyses = self.get_queryset()
        
        total_count = user_analyses.count()
        completed_count = user_analyses.filter(status='completed').count()
        failed_count = user_analyses.filter(status='failed').count()
        pending_count = user_analyses.filter(status='pending').count()
        
        return Response({
            'total_count': total_count,
            'completed_count': completed_count,
            'failed_count': failed_count,
            'pending_count': pending_count,
            'success_rate': (completed_count / total_count * 100) if total_count > 0 else 0
        })


